<template>
  <div class="invoice-detail">
    <section class="header">
      <a-page-header title="开票详情" :class="notBack ? 'hide-back' : ''" @back="$router.back()">
        <template #extra>
          <!-- 'DEL','EDIT','CANCEL','CLOSE'  //删除/编辑/作废/冲红 -->
          <a-button
              type="primary"
              @click="
              downloadFile(
                detail.e_invoice_link,
                `发票-${detail.owner_name}-${detail.invoice_time}.pdf`
              )
            "
              v-if="detail.e_invoice_link"
          >
            <template #icon>
              <DownloadOutlined/>
            </template>
            下载发票
          </a-button>
          <a-button
              type="primary"
              danger
              @click="
              downloadFile(
                detail.red_e_invoice_link,
                `冲红发票-${detail.owner_name}.pdf`
              )
            "
              v-if="detail.red_e_invoice_link"
          >
            <template #icon>
              <DownloadOutlined/>
            </template>
            下载冲红发票
          </a-button>
          <a-button
              key="CANCEL"
              v-if="topBtns.includes('CANCEL')"
              v-permission="['invoiceList', 'auth', 'cancel']"
              @click="handleCancel"
              type="primary"
              danger
          >
            作废
          </a-button>
          <a-button
              key="CLOSE"
              v-if="topBtns.includes('CLOSE')"
              v-permission="['invoiceList', 'auth', 'close']"
              @click="handleClose"
              :loading="redLoading"
              danger
          >
            冲红
          </a-button>
          <a-button
              key="DEL"
              danger
              v-if="topBtns.includes('DEL')"
              v-permission="['invoiceList', 'curd', 'delete']"
              @click="handleDel"
          >
            删除
          </a-button>
          <a-button
              key="EDIT"
              v-if="topBtns.includes('EDIT')"
              v-permission="['invoiceList', 'curd', 'edit']"
              @click="handleEdit"
          >
            编辑
          </a-button>
          <a-button type="primary"
                    v-if="detail.invoice_status == 6 || detail.invoice_status == 7 || detail.invoice_status == 9"
                    @click="ViewApproval(detail.approval_id)" ghost>查看审批
          </a-button>
        </template>
        <template #tags>
          <a-tag :color="invoiceStatusColor">
            {{ detail.invoice_status_txt }}
          </a-tag>
        </template>
        <a-row type="flex">
          <a-statistic
              title="申请开票金额"
              prefix="￥"
              :value="detail.apply_amounts"
          />
          <a-statistic
              style="margin-left: 40px"
              title="已开票金额"
              prefix="￥"
              :value="detail.invoice_prices || 0"
          />
        </a-row>

      </a-page-header>
    </section>

    <section class="content">
      <a-row :gutter="[12, 12]" :wrap="true">
        <a-col :span="24">
          <a-card title="发票信息">
            <a-descriptions :column="{ md: 6, sm: 4, xs: 1 }" layout="vertical">
              <a-descriptions-item label="开票类型">
                {{ detail.issue_type_txt }}
              </a-descriptions-item>
              <a-descriptions-item label="发票号码">
                {{ detail.invoice_number || "无" }}
              </a-descriptions-item>
              <a-descriptions-item label="发票代码">
                {{ detail.invoice_code || "无" }}
              </a-descriptions-item>
              <a-descriptions-item label="作废/冲红日期" v-if="detail.extra_time">
                {{ detail.extra_time }}
              </a-descriptions-item>
              <a-descriptions-item label="发票类型">
                {{ detail.invoice_type_txt }}
              </a-descriptions-item>
              <a-descriptions-item label="经办人">
            <span class="link" @click="showUserInfo(detail, 'cuser_uid')">
              {{ detail.cuser_name }}
            </span>
              </a-descriptions-item>
              <a-descriptions-item label="申请开票日期">
                {{ detail.apply_invoice_time }}
              </a-descriptions-item>
              <a-descriptions-item label="开票日期">
                {{ detail.invoice_time || "暂未开票" }}
              </a-descriptions-item>
              <a-descriptions-item label="发票备注">
                {{ detail.remark || "无" }}
              </a-descriptions-item>
              <a-descriptions-item label="电子发票" v-if="detail.can_e_invoice">
                <template v-if="detail.invoice_status == 3">
                  {{ detail.red_e_invoice_status_txt }}
                  <template v-if="detail.red_e_invoice_status == 3"
                  >({{ detail.red_e_invoice_error }})
                  </template
                  >
                  <div style="flex: none" v-if="detail.red_e_invoice_status == 3">
                    <a-button
                        type="link"
                        size="small"
                        class="ml-5"
                        :loading="redLoading"
                        @click="redEInvoice"
                    >重新冲红发票
                    </a-button
                    >
                  </div>
                </template>
                <template v-else>
                  {{ detail.e_invoice_status_txt }}
                  <template v-if="detail.e_invoice_status == 3"
                  >({{ detail.e_invoice_error }})
                  </template
                  >
                  <div style="flex: none" v-if="detail.e_invoice_status == 3">
                    <a-button
                        type="link"
                        size="small"
                        class="ml-5"
                        :loading="openLoading"
                        @click="openerEInvoice"
                    >重新开票
                    </a-button
                    >
                  </div>
                </template>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
        <a-col :xs="24" :md="12">
          <a-card title="购方信息">
            <a-descriptions :column="{ md: 3, sm: 2, xs: 1 }" layout="vertical">
              <a-descriptions-item label="公司名称">
                {{ detail.owner_name }}
              </a-descriptions-item>
              <a-descriptions-item label="纳税人识别号">
                {{ detail.buyer_tax_number || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="地址">
                {{ detail.buyer_address || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="开户行">
                {{ detail.buyer_bank || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="电话">
                {{ detail.buyer_phone || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="账户">
                {{ detail.buyer_account || "--" }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
        <a-col :xs="24" :md="12">
          <a-card title="售方信息">
            <a-descriptions :column="{ md: 3, sm: 2, xs: 1 }" layout="vertical">
              <a-descriptions-item label="公司名称">
                {{ detail.seller_name }}
              </a-descriptions-item>
              <a-descriptions-item label="纳税人识别号">
                {{ detail.saler_tax_number || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="地址">
                {{ detail.saler_address || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="开户行">
                {{ detail.saler_bank || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="电话">
                {{ detail.saler_phone || "--" }}
              </a-descriptions-item>
              <a-descriptions-item label="账户">
                {{ detail.saler_account || "--" }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
        <a-col :span="24">
          <a-card title="商品或服务明细">
            <a-alert show-icon>
              <template #message>
                <span>金额合计：</span>
                <span class="fw-bold">{{ invoiceTotal.price }}</span>
                <span> 元 </span>
                <span class="ml-10">税额合计：</span>
                <span class="fw-bold">{{ invoiceTotal.tax }}</span>
                <span> 元 </span>
                <span class="ml-10">价税合计：</span>
                <span class="fw-bold">{{ invoiceTotal.taxPrice }}</span>
                <span> 元 </span>
              </template>
            </a-alert>
            <a-table
                class="mt-10"
                :dataSource="invoiceList"
                :columns="INVOICE_LIST"
                rowKey="id"
                :pagination="false"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'txt'">
                  <span>{{ text || "--" }}</span>
                </template>
                <template v-if="column.key === 'tax_rate'">
                  <span>{{ text }}%</span>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
        <a-col :span="24">
          <a-card title="开票账单">
            <a-table
                :dataSource="billList"
                :columns="BILL_LIST"
                rowKey="id"
                :scroll="{ x: 'max-content' }"
                :pagination="false"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'actual_payment'">
                  <span>{{ text || 0 }}</span>
                </template>
                <template v-if="column.key === 'room_number'">
                  <span>{{ text.join("、") }}</span>
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="billDetail(text)">
                    查看详情
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
        <a-col :span="24" v-if="fileList.length > 0">
          <a-card title="附件">
            <div v-for="(file,index) in fileList" :key="index" style="margin-bottom: 10px" @click="fileView(file)">
             <span>{{ index+1 }}.&nbsp;</span> <a>{{ file }}</a>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </section>
    <edit-invoice
        :visible="editVisible"
        :editType="2"
        :content="editContent"
        @cancel="editVisible = false"
        @success="handleEditSuccess"
    />

    <UserDetail
        @request="$utils.commonRequest"
        :visible="userVisible"
        :uid="userId"
        :coordinateData="coordinateData"
        @cancel="userVisible = false"
    />

    <!-- 验证二维码   -->
    <InvoiceDocking
        :visible="invoiceVisible"
        :group_key="group_key"
        @closeModal="invoiceVisible = false"
    />
    <!-- 验证短信   -->
    <CodeVerify
        :visible="codeVisible"
        :group_key="group_key"
        @closeModal="codeVisible = false"
    />

    <a-modal v-model:visible="molapprove" width="450px" title="审批备注"
             @cancel="molapprove = false" footer centered>
      <div style="padding: 5px;">
        <a-alert type="info" v-if="!VoidApprove && apptype == 1" style="margin-bottom: 20px;">
          <template #message>
            发票作废暂未开启审批，点击”
            <span v-if="Voidis_admin" class="link" @click.stop="goSetting(Void_id)">配置</span>
            <span v-else class="link" style="cursor: not-allowed;">配置</span>
            “可快速设置。
          </template>
        </a-alert>

        <a-alert type="info" v-if="!FlushredApprove && apptype == 2" style="margin-bottom: 20px;">
          <template #message>
            开票冲红暂未开启审批，点击”
            <span v-if="Flushredis_admin" class="link"
                  @click.stop="goSetting(Flushred_id)">配置</span>
            <span v-else class="link" style="cursor: not-allowed;">配置</span>
            “可快速设置。
          </template>
        </a-alert>

        <div v-if="(VoidApprove && apptype == 1) || (FlushredApprove && apptype == 2)"
             style="margin-bottom: 25px;">
          <p>备注</p>
          <a-textarea v-model:value="approval_remark" :auto-size="{ minRows: 3, maxRows: 6 }"/>
        </div>

        <div style="width:100%;display: flex;justify-content: space-between;">
          <div style="color: #666666;line-height: 32px;">
            <span v-if="(VoidApprove && apptype == 1) || (FlushredApprove && apptype == 2)">
              <a-checkbox v-model:checked="checked">
                <span v-if="apptype == 1">确定作废此发票记录</span>
                <span v-if="apptype == 2">确定冲红此发票记录</span>
              </a-checkbox>
            </span>
          </div>

          <div>
            <a-button style="margin-right: 20px" @click="molapprove = false">取消</a-button>

            <a-button v-if="(VoidApprove && apptype == 1) || (FlushredApprove && apptype == 2)"
                      type="primary" :disabled="!checked" @click="onSubmit"> 确定&发起审批
            </a-button>
            <a-button v-else type="primary" @click="onSubmit"> 确定</a-button>
          </div>
        </div>
      </div>
    </a-modal>

    <notice-iframe
        :title="iframeTitle"
        :visible="iframeVisible"
        :url="iframeUrl"
        @cancel="iframeModalClose"
    />

    <!-- 账单详情 -->
    <BillDetailDrawer
        :visible="billDetailVisible"
        :id="billId"
        @cancel="onBillDetailClose"
    />

  </div>
</template>

<script>
import {message, Modal} from "ant-design-vue";
import {
  computed,
  defineComponent,
  reactive,
  toRefs,
  createVNode,
  ref,
  onUnmounted,
} from "vue";
import {useRoute, useRouter} from "vue-router";
import request from "../../../common/utils/request";
import EditInvoice from "../MakeInvoice/modules/EditInvoice.vue";
import InvoiceDocking from "./modules/InvoiceDocking.vue";
import CodeVerify from "./modules/CodeVerify.vue";
import {
  ExclamationCircleOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import {UserDetail} from "bl-common-vue3";
import utils from "@/common/utils/utils";
import NoticeIframe from "@/layouts/commonModules/notice/NoticeIframe.vue";
import store from "@/store";
import BillDetailDrawer from '@/views/bill/BillDetail/modules/BillDetailDrawer.vue'

export default defineComponent({
  name: "InvoiceDetail",
  components: {
    BillDetailDrawer,
    NoticeIframe,
    EditInvoice,
    DownloadOutlined,
    UserDetail,
    InvoiceDocking,
    CodeVerify,
    ExclamationCircleOutlined,
  },
  setup() {
    const $route = useRoute();
    const $router = useRouter();

    const notBack = $route.query.noBack;

    const state = reactive({
      group_key: $route.query.group_key,
      topBtns: [],
      detail: {},
      invoiceList: [],
      invoiceTotal: {},
      billList: [],
      editVisible: false,
      editContent: {},
      userVisible: false,
      userId: 0,
      coordinateData: {},
      openLoading: false, //开票loading
      redLoading: false, //冲红loading
      loopQuery: null,

      //作废审批
      VoidApprove: false,
      Voidis_admin: false,
      Void_id: '',
      //冲红审批
      FlushredApprove: false,
      Flushredis_admin: false,
      Flushred_id: '',

      apptype: '',
      molapprove: false,
      approval_remark: '',
      checked: false,

      iframeTitle: "查看详情",
      iframeVisible: false,
      iframeUrl: "",
      billId: 0,
      billDetailVisible: false,

      fileList:[],
      filePreviewUrl:''

    });

    // 编辑
    const handleEdit = () => {
      const {detail, invoiceList} = state;
      state.editContent = {
        owner_id: detail.owner_id,
        owner_name: detail.owner_name,
        owner_taxpayerIdNumber: detail.buyer_tax_number,
        owner_tel: detail.buyer_phone,
        owner_bank: detail.buyer_bank,
        owner_account: detail.buyer_account,
        owner_address: detail.buyer_address,
        seller_id: detail.seller_id,
        seller_name: detail.seller_name,
        seller_taxpayerIdNumber: detail.saler_tax_number,
        seller_tel: detail.saler_phone,
        seller_bank: detail.saler_bank,
        seller_account: detail.saler_account,
        seller_address: detail.saler_address,
        invoice_type: detail.invoice_type,
        issue_type: detail.issue_type,
        invoice_number: detail.invoice_number,
        invoice_code: detail.invoice_code,
        invoice_time: detail.invoice_time,
        remark: detail.remark,
        e_invoice_link: detail.e_invoice_link,
        splitList: invoiceList.map((item) => ({
          ...item,
          nopay_tax_price: item.unit_price,
        })),
        file: state.fileList.map((item, index) => {
          return {
            uid: index,
            name: item,
            status: 'done',
            url: item,
          }
        })
      };
      state.editVisible = true;
    };

    // 下载发票
    const downloadFile = (href, name) => {
      fetchDownloadFile({
        url: href,
        name,
      });
    };

    function fetchDownloadFile(data) {
      fetch(data.url, {
        method: "get",
        mode: "cors",
      })
          .then((response) => response.blob())
          .then((res) => {
            const downloadUrl = window.URL.createObjectURL(
                //new Blob() 对后端返回文件流类型处理
                new Blob([res], {
                  type:
                      data.type == "pdf"
                          ? "application/pdf"
                          : data.type == "word"
                              ? "application/msword"
                              : data.type == "xlsx"
                                  ? "application/vnd.ms-excel"
                                  : "",
                })
            );
            //word文档为msword,pdf文档为pdf
            const link = document.createElement("a");
            link.href = downloadUrl;
            link.setAttribute("download", data.name);
            document.body.appendChild(link);
            link.click();
            link.remove();
          })
          .catch((error) => {
            window.open(data.url);
          });
    }

    // 删除
    const handleDel = () => {
      modalConfirm(
          "确定删除此发票记录吗？",
          {method: "del", url: "/invoice/del"},
          () => {
            if (window?.microApp?.getData()?.isMainDrawer) {
              window?.microApp?.getData()?.closeDrawer(true);
            }else{
              $router.back();
            }
          }
      );
    };

    // 作废
    const handleCancel = () => {
      if (state.VoidApprove) {
        state.apptype = 1
        state.molapprove = true
      } else {
        modalConfirm(
            "确定作废此发票记录吗？",
            {
              method: "get",
              url: "/invoice/cancel",
            },
            () => {
              getDetail();
            }
        );
      }

    };

    // 冲红
    const handleClose = () => {
      if (state.FlushredApprove) {
        state.apptype = 2
        state.molapprove = true
      } else {
        modalConfirm(
            "确定冲红此发票记录吗？",
            {
              method: "get",
              url: "/invoice/close",
            },
            () => {
              getDetail();
            }
        );
      }

    };

    const onSubmit = () => {
      if (state.apptype == 1) {
        request
            .get("/org", "/invoice/cancel", {
              group_key: state.group_key,
              approval: state.VoidApprove,
              approval_remark: state.approval_remark,
              needMsg: true,
            })
            .then((res) => {
              getDetail();
            })
            .finally(() => {
              state.molapprove = false
            });

      } else {
        request
            .get("/org", "/invoice/close", {
              group_key: state.group_key,
              approval: state.FlushredApprove,
              approval_remark: state.approval_remark,
              needMsg: true,
            })
            .then((res) => {
              getDetail();
            })
            .finally(() => {
              state.molapprove = false
            });
      }
    }

    const modalConfirm = (content, req, successCallback) => {
      Modal.confirm({
        title: () => "提示",
        content: () => content,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          state.redLoading = req.url == "/invoice/close" ? true : false;
          request[req.method]("/org", req.url, {
            group_key: state.group_key,
            needMsg: true,
          })
              .then((res) => {
                message.success(res.msg || "操作成功！");
                successCallback && successCallback();
              })
              .catch((error) => {
                console.log(error);
                if (req.url == "/invoice/close") {
                  if (error.code == 4001) {
                    codeVisible.value = true;
                  } else if (error.code == 4002) {
                    invoiceVisible.value = true;
                  }
                }
              })
              .finally(() => {
                state.redLoading = false;
              });
        },
      });
    };

    const invoiceVisible = ref(false);
    const codeVisible = ref(false);
    const openerEInvoice = () => {
      state.openLoading = true;
      request
          .post("/org", "/invoice/openerEInvoice", {
            group_key: state.group_key,
          })
          .then((res) => {
            console.log(res);
            message.success(res.msg || "操作成功！");
            getDetail();
          })
          .catch((error) => {
            console.log(error);
            if (error.code == 4001) {
              codeVisible.value = true;
            } else if (error.code == 4002) {
              invoiceVisible.value = true;
            }
          })
          .finally(() => {
            state.openLoading = false;
          });
    };

    const redEInvoice = () => {
      state.redLoading = true;
      request
          .post("/org", "/invoice/redEInvoice", {
            group_key: state.group_key,
          })
          .then((res) => {
            message.success(res.msg || "操作成功！");
            getDetail();
          })
          .catch((error) => {
            console.log(error);
            if (error.code == 4001) {
              codeVisible.value = true;
            } else if (error.code == 4002) {
              invoiceVisible.value = true;
            }
          })
          .finally(() => {
            state.redLoading = false;
          });
    };

    const handleEditSuccess = (content) => {
      console.log("handleEditSuccess", content);
      if (content.file.length > 0) {
        content.file = content.file.map((item) => item.url)
      }
      state.editVisible = false;
      request
          .put("/org", "/invoice/edit", {
            group_key: state.group_key,
            invoice_arr: content,
            needMsg: true,
          })
          .then((res) => {
            message.success(res.msg || "保存成功！");
            getDetail();
          });
    };

    // 账单详情
    const billDetail = (id) => {
      state.billId = id;
      state.billDetailVisible = true;
    };

    const onBillDetailClose = () => {
      state.billId = 0;
      state.billDetailVisible = false;
    }

    // 商品或服务的总计信息
    const getInvoiceTotal = () => {
      let taxTotal = 0,
          priceTotal = 0,
          taxPriceTotal = 0;
      state.invoiceList.forEach((item) => {
        taxTotal = (Number(taxTotal) + Number(item.tax_amount)).toFixed(2);
        priceTotal = (Number(priceTotal) + Number(item.unit_price)).toFixed(2);
        taxPriceTotal = (
            Number(taxPriceTotal) + Number(item.apply_invoice_amount)
        ).toFixed(2);
      });
      state.invoiceTotal = {
        tax: taxTotal,
        price: priceTotal,
        taxPrice: taxPriceTotal,
      };
    };

    const clearLoop = () => {
      if (state.loopQuery) {
        clearTimeout(state.loopQuery);
      }
    };

    // 查看电子发票状态
    const getEInvoiceInfo = (is_red) => {
      let param = {group_key: state.group_key};
      if (is_red) {
        param.is_red = 1;
      }
      request
          .post("/org", "/invoice/queryEInvoice", param)
          .then((res) => {
            console.log(res);
            const status = res.status;
            if (status == 2) {
              state.loopQuery = setTimeout(() => {
                getEInvoiceInfo(is_red);
              }, 3000);
            } else {
              clearLoop();
              getDetail();
            }
          })
          .catch((error) => {
            console.log(error);
            clearLoop();
          });
    };

    const getDetail = () => {
      request
          .get("/org", "/bill/invoiceDetail", {
            group_key: state.group_key,
          })
          .then((res) => {
            const {billData, invoiceDetail, mainDetail, operateButton} =
                res.list;
            state.topBtns = operateButton;
            state.detail = mainDetail;
            state.detail.approve_status = mainDetail.approve_status || undefined;
            state.invoiceList = invoiceDetail;
            state.filePreviewUrl = res.list.previewUrl
            state.fileList = []
            invoiceDetail.forEach((item)=>{
              if(item.file){
                state.fileList.push(...item.file) 
              }
            })
            getInvoiceTotal();
            state.billList = billData;
            /*if (state.detail.approve_status == 1) {
              getApprovalInfo();
            }*/
            if (state.detail.e_invoice_status == 2) {
              getEInvoiceInfo(false);
            } else if (state.detail.red_e_invoice_status == 2) {
              getEInvoiceInfo(true);
            } else {
              clearLoop();
            }
          });
    };

    onUnmounted(() => {
      clearLoop();
    });

    const invoiceStatusColor = computed(() => {
      if (state.detail.invoice_status == 1) {
        return "#1677ff";
      } else if (state.detail.invoice_status == 2) {
        return "#00b578";
      } else if (state.detail.invoice_status == 3) {
        return "#ff3141";
      } else if (state.detail.invoice_status == 6) {
        return "#999999";
      } else if (state.detail.invoice_status == 7) {
        return "#e3c738";
      } else if (state.detail.invoice_status == 8) {
        return "#cacaca";
      } else if (state.detail.invoice_status == 9) {
        return "#ff3141";
      } else {
        return "#666666";
      }
    });

    const ViewApproval = (approval_id) => {

      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: '审批详情',
              closable: true,
              maskClosable: true,
              visible: true,
              width: 1000,
              bodyStyle: {
                height: '100%',
                boxSizing: 'border-box',
                overflowY: 'auto',
                background: '#ffffff'
              },
              destroyOnClose: true,
            },
            microId: `approvalDetailMessage`,
            app: 'workApproval',
            url: `/approval/detail?id=${approval_id}`,
          }
        })
      }
      state.iframeUrl = `${link}${link.indexOf("?") === -1 ? "?" : "&"}org_token=${utils.getStorage("org_token")}&from=pc`;
      state.iframeTitle = state.detail.issue_type_txt;
      state.iframeVisible = true;
    }

    const iframeModalClose = () => {
      state.iframeVisible = false;
      state.iframeTitle = "";
      state.iframeUrl = "";
      getDetail();
    };

    const getVoid = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'invoice_nullify'
      }).then((res) => {
        state.VoidApprove = res.info.process    //判断是否开启
        state.Voidis_admin = res.info.is_admin    //判断是否有权限
        state.Void_id = res.info.id
      });
    };

    const getFlushred = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'invoice_red'
      }).then((res) => {
        state.FlushredApprove = res.info.process    //判断是否开启
        state.Flushredis_admin = res.info.is_admin    //判断是否有权限
        state.Flushred_id = res.info.id
      });
    };

    const getSetting = () => {
      if (state.apptype == 1) {
        getVoid()
      } else {
        getFlushred()
      }
    }
    const goSetting = (id, index) => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    const fileView = (fileUrl)=>{
      window.microApp.forceDispatch(
        {
          type: "previewFile",
          visible: true,
          file:{
            url: fileUrl,
          },
          filePreviewUrl:`${state.filePreviewUrl}?file_url=${encodeURIComponent(fileUrl)}`
        }
      );
    }

    const init = () => {
      getVoid()
      getFlushred()
      getDetail();
    };
    init();

    const showUserInfo = (info, field) => {
      if (!info[field]) {
        return;
      }
      state.userId = info[field];
      state.coordinateData = window.event;
      setTimeout(() => {
        state.userVisible = true;
      }, 50);
    };

    return {
      invoiceStatusColor,
      INVOICE_LIST,
      BILL_LIST,
      ...toRefs(state),
      billDetail,
      handleEdit,
      handleEditSuccess,
      handleDel,
      handleCancel,
      handleClose,
      downloadFile,
      openerEInvoice,
      redEInvoice,
      showUserInfo,
      invoiceVisible,
      codeVisible,
      getVoid,
      getFlushred,
      goSetting,
      onSubmit,
      ViewApproval,
      iframeModalClose,
      onBillDetailClose,
      fileView,
      notBack
    };
  },
});
const INVOICE_LIST = [
  {
    title: "商品或服务名称",
    key: "tax_cost_name",
    dataIndex: "tax_cost_name",
  },
  {
    title: "规格型号",
    key: "txt",
    dataIndex: "specs",
  },
  {
    title: "单位",
    key: "txt",
    dataIndex: "invoice_unit",
  },
  {
    title: "数量",
    key: "total",
    dataIndex: "total",
  },
  {
    title: "单价",
    key: "unit_price",
    dataIndex: "unit_price",
  },
  {
    title: "金额",
    key: "unit_price_2",
    dataIndex: "unit_price",
  },
  {
    title: "税率",
    key: "tax_rate",
    dataIndex: "tax_rate",
  },
  {
    title: "价税合计",
    key: "apply_invoice_amount",
    dataIndex: "apply_invoice_amount",
  },
];
const BILL_LIST = [
  {
    title: "项目",
    key: "villageName",
    dataIndex: "villageName",
    width: 160,
  },
  {
    title: "楼宇",
    key: "buildName",
    dataIndex: "buildName",
    width: 160,
  },
  {
    title: "房号",
    key: "room_number",
    dataIndex: "room_number",
    width: 160,
  },
  {
    title: "账单类型",
    key: "bill_type_txt",
    dataIndex: "bill_type_txt",
    width: 120,
  },
  {
    title: "费用类型",
    key: "cost_type_txt",
    dataIndex: "cost_type_txt",
    width: 120,
  },
  {
    title: "应收",
    key: "receivable_payment",
    dataIndex: "receivable_payment",
    width: 160,
  },
  {
    title: "实收",
    key: "actual_payment",
    dataIndex: "actual_payment",
    width: 160,
  },
  {
    title: "开票金额",
    key: "invoice_amount",
    dataIndex: "invoice_amount",
    width: 160,
  },
  {
    title: "应收日期",
    key: "receivable_payment_date",
    dataIndex: "receivable_payment_date",
    width: 160,
  },
  {
    title: "结清状态",
    key: "settle_status_txt",
    dataIndex: "settle_status_txt",
    width: 120,
  },
  {
    title: "操作",
    key: "action",
    dataIndex: "id",
    width: 120,
    fixed: "right",
  },
];
</script>

<style lang="less" scoped>
.invoice-detail {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    background: #fff;
    width: 100%;
    padding-left: 1px;
    border-bottom: 1px solid #f0f2f5;
    .hide-back{
      :deep(.ant-page-header-back) {
        display: none;
      }
    }
  }

  .content {
    flex: 1;
    padding: 10px;
    overflow: hidden auto;
  }
}

:deep(.ant-descriptions-item-label ) {
  margin-bottom: -8px;
}

:deep(.ant-descriptions-item-label::after ) {
  content: ''
}

:deep(.ant-descriptions-item-content) {
  color: black;
}


</style>
